package com.lightspring.core.io;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ClassUtil;
import com.lightspring.utils.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 类路径下加载文件信息
 * @author 毅航
 * @date 2023/11/4 8:23
 */
public class ClassPathResource implements Resource {

    /**
     * 路径信息和类加载器
     * 通过类加载内容去加载相关类配置信息
     */
    private final String path;
    private  ClassLoader classLoader;
    private  Class<?> clazz;

    public ClassPathResource(String path) {
        this(path,(ClassLoader) null);
    }

    public ClassPathResource(String path,  Class<?> clazz) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        this.clazz = clazz;
    }

    public ClassPathResource(String path,ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader :
                ClassUtils.getDefaultClassLoader());
    }

    /**
     * @author: 毅航
     * @description: 从对应路径处的文件内容中返回相关流信息
     * @date: 2023/11/4 8:23
     * @parms
     * @return
     */
    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = ClassUtils.getDefaultClassLoader().getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException(this.path +
                    " cannot be opened because it does not exist");

        }
        return is;
    }

    @Override
    public boolean exists() {
        return resolveURL() != null;
    }

    protected URL resolveURL() {
        try {
            if (this.clazz != null) {
                return this.clazz.getResource(this.path);
            }
            else if (this.classLoader != null) {
                return this.classLoader.getResource(this.path);
            }
            else {
                return ClassLoader.getSystemResource(this.path);
            }
        } catch (IllegalArgumentException ex) {
            return null;
        }
    }
}
